'use strict';

angular.module('flowableModeler')
    .controller('ProcessesCtrl', ['$rootScope', '$scope', '$translate', '$http', '$timeout', '$location', '$modal',
        function ($rootScope, $scope, $translate, $http, $timeout, $location, $modal) {
//         $.ajax({
//           type: "GET",
//           url:
//             "填写你的数据接口地址",
//           dataType: "json",
//           success: function(response) {
//                aboutData = response;
//             //写在获取数据成功后你想进行的操作
//           },
//           error: function() {
//             alert("请求失败");
//           }
//         });
            // Main page (needed for visual indicator of current page)
            $rootScope.setMainPageById('processes');
            $rootScope.formItems = undefined;

            // get latest thumbnails
            $scope.imageVersion = Date.now();

            let reg = new RegExp("(^|&)" + "tenant_id" + "=([^&]*)(&|$)", "i");
            let r = window.location.search.substr(1).match(reg);
            let retTenantId = null;
            if (r != null) {
                // retTenantId = 1235;
                retTenantId = unescape(r[2]);
            }


            _internalCreateModal({
                template: 'views/popup/process-create.html?version=' + Date.now()
            }, $modal, $scope);

            $scope.model = {
                filters: [
                    {id: 'processes', labelKey: 'PROCESSES'}
                ],

                sorts: [
                    {id: 'modifiedDesc', labelKey: 'MODIFIED-DESC'},
                    {id: 'modifiedAsc', labelKey: 'MODIFIED-ASC'},
                    {id: 'nameAsc', labelKey: 'NAME-ASC'},
                    {id: 'nameDesc', labelKey: 'NAME-DESC'}
                ]
            };

            if ($rootScope.modelFilter) {
                $scope.model.activeFilter = $rootScope.modelFilter.filter;
                $scope.model.activeSort = $rootScope.modelFilter.sort;
                $scope.model.filterText = $rootScope.modelFilter.filterText;

            } else {
                // By default, show first filter and use first sort
                $scope.model.activeFilter = $scope.model.filters[0];
                $scope.model.activeSort = $scope.model.sorts[0];
                $rootScope.modelFilter = {
                    filter: $scope.model.activeFilter,
                    sort: $scope.model.activeSort,
                    filterText: '',
                };
            }

            $scope.activateFilter = function (filter) {
                $scope.model.activeFilter = filter;
                $rootScope.modelFilter.filter = filter;
                $scope.loadProcesses();
            };

            $scope.activateSort = function (sort) {
                $scope.model.activeSort = sort;
                $rootScope.modelFilter.sort = sort;
                $scope.loadProcesses();
            };

            $scope.loadProcesses = function () {
                $scope.model.loading = true;

                var params = {
                    filter: $scope.model.activeFilter.id,
                    sort: $scope.model.activeSort.id,
                    modelType: 0,
                    tenantId:retTenantId,
                };

                if ($scope.model.filterText && $scope.model.filterText != '') {
                    params.filterText = $scope.model.filterText;
                }

                $http({
                    method: 'GET',
                    url: FLOWABLE.APP_URL.getModelsUrl(),
                    params: params
                }).success(function (data, status, headers, config) {

                    $scope.model.processes = data;
                    $scope.model.loading = false;
                }).error(function (data, status, headers, config) {
                    console.log('Something went wrong: ' + data);
                    $scope.model.loading = false;
                });
            };

            var timeoutFilter = function () {
                $scope.model.isFilterDelayed = true;
                $timeout(function () {
                    $scope.model.isFilterDelayed = false;
                    if ($scope.model.isFilterUpdated) {
                        $scope.model.isFilterUpdated = false;
                        timeoutFilter();
                    } else {
                        $scope.model.filterText = $scope.model.pendingFilterText;
                        $rootScope.modelFilter.filterText = $scope.model.filterText;
                        $scope.loadProcesses();
                    }
                }, 500);
            };

            $scope.filterDelayed = function () {
                if ($scope.model.isFilterDelayed) {
                    $scope.model.isFilterUpdated = true;
                } else {
                    timeoutFilter();
                }
            };

            $scope.createProcess = function (mode) {
                var modalInstance = _internalCreateModal({
                    template: 'views/popup/process-create.html?version=' + Date.now()
                }, $modal, $scope);
            };

            $scope.importProcess = function () {
                _internalCreateModal({
                    template: 'views/popup/process-import.html?version=' + Date.now()
                }, $modal, $scope);
            };

            $scope.showProcessDetails = function (process) {
                if (process) {
                    $rootScope.editorHistory = [];
                    $location.path("/processes/" + process.id);
                }
            };

            $scope.editProcessDetails = function (process) {
                if (process) {
                    $rootScope.editorHistory = [];
                    $location.path("/editor/" + process.id);
                }
            };

            // Finally, load initial processes
            $scope.loadProcesses();
        }]);

angular.module('flowableModeler')
    .controller('CreateNewProcessModelCtrl', ['$rootScope', '$scope', '$modal', '$http', '$location',
        function ($rootScope, $scope, $modal, $http, $location) {
            var date = new Date();


            //读取传入的tenant_id
            let reg = new RegExp("(^|&)" + "tenant_id" + "=([^&]*)(&|$)", "i");
            let tenant_id = window.location.search.substr(1).match(reg);
            if (tenant_id != null)
                tenant_id = unescape(tenant_id[2]);
            $scope.model = {
                loading: false,
                process: {
                    name: '',
                    key: 'key' + date.getTime(),
                    description: '',
                    modelType: 0,
                    tenantId:tenant_id
                }
            };

            $scope.model.process.name=Date.now();
            if (!$scope.model.process.name || $scope.model.process.name.length == 0 ||
                !$scope.model.process.key || $scope.model.process.key.length == 0) {

                return;
            }

            $scope.model.loading = true;

            $http({
                method: 'POST',
                url: FLOWABLE.APP_URL.getModelsUrl(),
                data: $scope.model.process
            }).success(function (data) {
                $scope.$hide();

                $scope.model.loading = false;
                $rootScope.editorHistory = [];
                $location.path("/editor/" + data.id);
            }).error(function (data, status, headers, config) {
                $scope.model.loading = false;
                $scope.model.errorMessage = data.message;
            });






            if ($scope.initialModelType !== undefined) {
                $scope.model.process.modelType = $scope.initialModelType;
            }

            $scope.ok = function () {

                if (!$scope.model.process.name || $scope.model.process.name.length == 0 ||
                    !$scope.model.process.key || $scope.model.process.key.length == 0) {

                    return;
                }

                $scope.model.loading = true;

                $http({
                    method: 'POST',
                    url: FLOWABLE.APP_URL.getModelsUrl(),
                    data: $scope.model.process
                }).success(function (data) {
                    $scope.$hide();

                    $scope.model.loading = false;
                    $rootScope.editorHistory = [];
                    $location.path("/editor/" + data.id);
                }).error(function (data, status, headers, config) {
                    $scope.model.loading = false;
                    $scope.model.errorMessage = data.message;
                });
            };

            $scope.cancel = function () {
                if (!$scope.model.loading) {
                    $scope.$hide();
                }
            };
        }]);

angular.module('flowableModeler')
    .controller('DuplicateProcessModelCtrl', ['$rootScope', '$scope', '$modal', '$http', '$location',
        function ($rootScope, $scope, $modal, $http, $location) {

            $scope.model = {
                loading: false,
                process: {
                    name: '',
                    key: '',
                    description: ''
                }
            };

            if ($scope.originalModel) {
                //clone the model
                $scope.model.process.name = $scope.originalModel.process.name;
                $scope.model.process.key = $scope.originalModel.process.key;
                $scope.model.process.description = $scope.originalModel.process.description;
                $scope.model.process.id = $scope.originalModel.process.id;
                $scope.model.process.modelType = $scope.originalModel.process.modelType;
            }

            $scope.ok = function () {

                if (!$scope.model.process.name || $scope.model.process.name.length == 0 ||
                    !$scope.model.process.key || $scope.model.process.key.length == 0) {

                    return;
                }

                $scope.model.loading = true;

                $http({
                    method: 'POST',
                    url: FLOWABLE.APP_URL.getCloneModelsUrl($scope.model.process.id),
                    data: $scope.model.process
                }).success(function (data) {
                    $scope.$hide();

                    $scope.model.loading = false;
                    $rootScope.editorHistory = [];
                    $location.path("/editor/" + data.id);
                }).error(function (data, status, headers, config) {
                    $scope.model.loading = false;
                    $scope.model.errorMessage = data.message;
                });
            };

            $scope.cancel = function () {
                if (!$scope.model.loading) {
                    $scope.$hide();
                }
            };
        }]);

angular.module('flowableModeler')
    .controller('ImportProcessModelCtrl', ['$rootScope', '$scope', '$http', 'Upload', '$location', function ($rootScope, $scope, $http, Upload, $location) {

        $scope.model = {
            loading: false
        };

        $scope.onFileSelect = function ($files, isIE) {

            $scope.model.loading = true;

            for (var i = 0; i < $files.length; i++) {
                var file = $files[i];

                var url;
                if (isIE) {
                    url = FLOWABLE.APP_URL.getImportProcessModelTextUrl();
                } else {
                    url = FLOWABLE.APP_URL.getImportProcessModelUrl();
                }

                Upload.upload({
                    url: url,
                    method: 'POST',
                    file: file
                }).progress(function (evt) {
                    $scope.model.uploadProgress = parseInt(100.0 * evt.loaded / evt.total);

                }).success(function (data) {
                    $scope.model.loading = false;

                    $location.path("/editor/" + data.id);
                    $scope.$hide();

                }).error(function (data) {

                    if (data && data.message) {
                        $scope.model.errorMessage = data.message;
                    }

                    $scope.model.error = true;
                    $scope.model.loading = false;
                });
            }
        };

        $scope.cancel = function () {
            if (!$scope.model.loading) {
                $scope.$hide();
            }
        };
    }]);
